package ex1;
import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.Format;
import java.util.Date;

/* This is the server side of the TCP example
   It waits for a connection request from a client, reads a line
   from the socket, converts that string to upper case and then
   sends it back.  It then waits for another connection
*/

class TCPServer {
    public static void main (String args[])
      throws Exception
      /* if you have time at the end take a look at the exceptions that might be raised and think about nicer ways of handling them */
      {
	String clientSentence;
	String capitalisedSentence;

	/* a ServerSocket is a special kind of socket that listens
	 for requests from clients.  When a request arrives, it
	 returns a new socket that is specific to that connection
	 NOTE you will probably have to change the port number,
	 since only one server can listen on a socket at a time,
	 and one of your classmates has probably got there first!
	 pick any number between 1024 and 16000-odd
         the the whiteboard in the labs for open socket range there
         */
	ServerSocket welcomeSocket = new ServerSocket(4321);

	while (true) {
	    // the accept() method waits until a connection request
	    // arrives, and then returns a socket specific to that
	    // connection.
	    Socket clientSocket = welcomeSocket.accept();

	    // Exercise One:
	    // put a line here that prints out the internet address
	    // of the client - look up Socket methods in the Java API

	    // Thought:
	    // What happens if two clients try to connect more or less
	    // simultaneously?  What if you uncommented the next line:
	    //	    Thread.sleep(10000);

	    // Create a zillion Java objects just do so simple input
	    // (see the comments in the client)
	    BufferedReader inFromClient =
		      new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
	    DataOutputStream outToClient =
		      new DataOutputStream(clientSocket.getOutputStream());

	    // read a sentence from the client - this waits
	    // until the client has actually sent something
	    clientSentence = inFromClient.readLine();
	    if(clientSentence.equals("terminate")){
		    capitalisedSentence = clientSentence.toUpperCase();

		    // and send it back to the client
		    Date now = new Date(System.currentTimeMillis());
		    String s = DateFormat.getDateInstance().format(now);
		    outToClient.writeBytes(s + "\n");
		    break;
	    }

	    // do the actual job
	    Date now = new Date(System.currentTimeMillis());
	    String s = DateFormat.getDateInstance().format(now);
	    outToClient.writeBytes(s + "\n");
	    
	    // it would be good form to close the socket here,
	    // but I didn't write this code
	 }
 }
}
